import express from "express";
import cors from "cors";
import helmet from "helmet";
import morgan from "morgan";
import { notFoundHandler } from "./framework/middlewares/notFoundHandler";
import { errorHandler } from './framework/middlewares/errorHandler'
import { apiRouter } from "./routes";
import { logger, stream } from './framework/config/logger'; // 导入日志配置
import { performanceMonitor } from './framework/middlewares/performanceMonitor'

import initializeSources from "./sources/registrys";

class App {
  public app: express.Application;

  constructor() {
    this.app = express();
    this.config();
    this.routes();
    this.errorHandling();
  }

  private config(): void {
    this.app.use(helmet());
    this.app.use(express.json({ limit: "10mb" }));
    this.app.use(express.urlencoded({ extended: true }));
    this.app.use(cors());
    this.app.use(morgan('combined', { stream })); // 使用 Morgan 记录 HTTP 请求日志
    this.app.use(performanceMonitor); // 使用Winston来记录每个请求的响应时间，并添加一些性能监控的中间件
    this.initSources()
  }

  private routes(): void {

    // 添加请求日志中间件
    this.app.use((req, res, next) => {
      logger.info(`${req.method} ${req.originalUrl}`);
      next();
    });

    this.app.get("/", (req, res) => {
      res.redirect("https://ywfstudio.site/api/onesay/getRandomOneSay");
    });
    // 注册路由
    this.app.use("/api", apiRouter);
  }

  private errorHandling(): void {
    this.app.use(notFoundHandler);
    this.app.use(errorHandler);
  }

  /**
   * 热搜数据源
   */
  private initSources(): void {
    initializeSources()
      .then(sources => {
        const sList = Object.keys(sources);
        logger.info(`成功加载 ${sList.length} 个数据源-->[ ${sList} ]`);
      })
      .catch(error => {
        logger.error('初始化数据源失败:', error);
      });
  }

}

export default new App().app;
